package com.yt.lxh.common.service;

import cn.hutool.core.date.DateUtil;
import com.yt.lxh.common.exception.FileException;
import com.yt.lxh.common.result.ResultCodeEnum;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Component
public class MinioService {

    @Autowired
    private MinioClient minioClient;

    @Value("${lxh.minio.bucketName:luxuehe-bucket}")
    private String bucketName;

    @Value("${lxh.minio.endpoint:http://localhost:9000}")
    private String endpoint;

    /**
     * 上传文件
     * @param multipartFile 上传的文件对象
     * @return
     */
    public String uploadByFile(MultipartFile multipartFile) {
        String url;
        try {
//            createBucket();
            String filePath = getFileName(multipartFile.getOriginalFilename());
            //文件上传
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName)
                            .object(filePath)
                            .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                            .build());
            // 获取上传文件在minio路径
            url = endpoint + "/" + bucketName + "/" + filePath;
        } catch (Exception e) {
            log.error("Minio ---> 文件上传失败: {}", e.getMessage());
            throw new FileException(ResultCodeEnum.FILE_UPLOAD_FAIL);
        }
        return url;
    }

    /**
     * 删除文件
     * @param objectKey 文件名
     * @return
     */
    public boolean removeFile(String objectKey) {
        try {
            String s = subStringByFileName(objectKey);
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(s).build());
            return true;
        } catch (Exception e) {
            log.error("Minio ---> 文件删除失败或未找到: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 下载文件
     * @param objectKey 文件名
     * @return
     */
    public InputStream downloadFile(String objectKey) {
        try {
            String s = subStringByFileName(objectKey);
            // 返回文件流
            return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(s).build());
        } catch (Exception e) {
            log.error("Minio ---> 文件下载失败: {}", e.getMessage());
        }
        return null;
    }

    // 创建一个桶
    private void createBucket() {
        // 判断桶是否存在
        BucketExistsArgs exist = BucketExistsArgs.builder().bucket(bucketName).build();
        try {
            boolean result = minioClient.bucketExists(exist);
            if(!result){
                MakeBucketArgs create = MakeBucketArgs.builder().bucket(bucketName).build();
                minioClient.makeBucket(create);
            }
        } catch (Exception e) {
            log.error("Minio ---> 桶‘{}’，创建失败! 异常信息：{}", bucketName, e.getMessage());
        }
    }

    /**
     * 获取上传文件名称
     * 每个上传文件名称唯一的 uuid生成01.jpg
     * 根据当前日期对上传文件进行分组 20231101
     * 20231101/01.jpg
     * @param fileName
     * @return
     */
    private String getFileName(String fileName) {
        String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
        String fileNameByUUID = UUID.randomUUID().toString().replaceAll("-","")+fileName;
        String filePath = dateDir +"/"+fileNameByUUID;
        return filePath;
    }

    /**
     * 截取文件名
     * @param s
     * @return
     */
    private String subStringByFileName(String s) {
        return s.substring(s.lastIndexOf("/", s.lastIndexOf("/") -1));
    }
}

